/**
 * SubstringFormatter
 *
 * @author Chris Pratt
 *
 * 2/24/2010
 */
package com.anodyzed.onyx.text;

public class SubstringFormatter extends TextFormatter {
  private int st;
  private int nd;

  /**
   * Constructor
   *  
   * @param parent The parent TextFormat 
   * @param key The Argument Index of Map Key for this node 
   * @param bean The Additional Bean Reference String 
   * @param range The Substring Range
   */
  public SubstringFormatter (TextFormat parent,CharSequence key,CharSequence bean,CharSequence range) {
    super(parent,key,bean);
    int sep;
    int step = 1;
    String rng = range.toString();
    if((sep = rng.indexOf('-')) == -1) {
      if((sep = rng.indexOf(',')) == -1) {
        if((sep = rng.indexOf("...")) == -1) {
          sep = rng.indexOf("..");
          step = 2;
        } else {
          step = 3;
        }
      }
    }
    if(sep != -1) {
      st = Integer.parseInt(rng.substring(0,sep));
      nd = Integer.parseInt(rng.substring(sep + step));
    } else {
      st = Integer.parseInt(rng);
      nd = -1;
    }
  } //SubstringFormatter

  /**
   * Constructor
   *  
   * @param parent The parent TextFormat 
   * @param key The Argument Index of Map Key for this node 
   * @param bean The Additional Bean Reference String 
   */
  public SubstringFormatter (TextFormat parent,CharSequence key,CharSequence bean) {
    super(parent,key,bean);
    throw new IllegalArgumentException("Substring Formatter requires a range string");
  } //SubstringFormatter

  /**
   * Return a substring of the string value
   *
   * @param args The Formatting Arguments
   * @return The Formatted String
   */
  @Override
  public String toString (Object... args) {
    Object o = getValue(args);
    if(o != null) {
      String s = o.toString();
      int l = s.length();
      if(st < l) {
        return (nd == -1) ? s.substring(st) : s.substring(st,Math.min(nd,l));
      }
      return "";
    }
    return null;
  } //toString

} //*SubstringFormatter
